// user.js - 用户状态管理
import { defineStore } from 'pinia'
import { login, logout, getUserInfo, register } from '../api/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: null,
    // 登录状态
    isLoggedIn: false,
    // 令牌
    token: null
  }),
  
  getters: {
    // 获取用户角色
    userRole: (state) => state.userInfo?.role || null,
    // 检查是否为管理员
    isAdmin: (state) => state.userInfo?.role === 1
  },
  
  actions: {
    // 登录
    async loginAction(loginData) {
      try {
        const res = await login(loginData)
        this.token = res.data.token
        this.userInfo = res.data.user
        this.isLoggedIn = true
        
        // 存储到本地存储
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('userInfo', JSON.stringify(res.data.user))
        
        return Promise.resolve(res)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 注册
    async registerAction(registerData) {
      try {
        const res = await register(registerData)
        return Promise.resolve(res)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 退出登录
    async logoutAction() {
      try {
        await logout()
        this.resetUserInfo()
        return Promise.resolve()
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 获取用户信息
    async getUserInfoAction() {
      try {
        const res = await getUserInfo()
        this.userInfo = res.data
        this.isLoggedIn = true
        return Promise.resolve(res)
      } catch (error) {
        this.resetUserInfo()
        return Promise.reject(error)
      }
    },
    
    // 初始化用户状态（从本地存储获取用户信息）
    initUserState() {
      const storedToken = localStorage.getItem('token')
      const storedUserInfo = localStorage.getItem('userInfo')
      
      if (storedToken && storedUserInfo) {
        this.token = storedToken
        this.userInfo = JSON.parse(storedUserInfo)
        this.isLoggedIn = true
      }
    },
    
    // 重置用户信息
    resetUserInfo() {
      this.userInfo = null
      this.isLoggedIn = false
      this.token = null
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  }
}) 